package com.zhiche.lisa.bms.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.dao.model.interfacelog.InterfaceLog;
import com.zhiche.lisa.bms.pojo.dto.util.FcPayApplyDTO;
import com.zhiche.lisa.bms.pojo.dto.util.FcPayApplyReturnDTO;
import com.zhiche.lisa.bms.service.utils.common.Cache;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: liuanshun
 * @Description:
 * @Date: Create in 11:35 2018/11/23
 */
@Component
public class PayApiUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PayApiUtil.class);
    /**
     * 创建值可以复用的定时缓存(默认时效10M)
     */
    private final static Cache<Object> payApiUtilCache = new Cache<Object>(true).setDateReusable(false);

    @Value("${lisa.payApi.url}")
    private String url;
    @Value("${lisa.payApi.createPayapply}")
    private String createPayapply;
    @Value("${lisa.payApi.getPayApplyAudit}")
    private String getPayApplyAudit;
    @Value("${lisa.payApi.socketTimeout}")
    private Integer socketTimeout;

    @Autowired
    private UacUtil uacUtil;
    @Autowired
    private InterfaceLogUtil interfaceLogUtil;

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        String synchroToken;
        if (payApiUtilCache.checkCacheName("synchroToken")) {
            synchroToken = Objects.toString(payApiUtilCache.get("synchroToken"), "");
        } else {
            synchroToken = uacUtil.getToken("15110288389", "123456");
            if (Strings.isNullOrEmpty(synchroToken)) {
                throw new BaseException("无法获取油卡支付同步Token");
            }
            //2小时token失效，提前10分钟自动清除
            payApiUtilCache.put("synchroToken", synchroToken, Cache.CACHE_HOLD_TIME_2H - Cache.CACHE_HOLD_TIME_10M);
        }
        return synchroToken;
    }

    /**
     * 创建万金油油卡记录
     *
     * @param fcPayApplyDTO
     * @return
     */
    public RestfulResponse<String> createPayapply(FcPayApplyDTO fcPayApplyDTO) {
        String token = this.getToken();
        RestfulResponse<String> stringRestfulResponse = new RestfulResponse<>();
        InterfaceLog interfaceLog = new InterfaceLog();
        try {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", "Bearer " + token));
            // 发送请求
            String param = JSON.toJSONString(fcPayApplyDTO);
            interfaceLogUtil.setCallerPartyCommonLog(interfaceLog, param, url + createPayapply);

            String strReturn = HttpClientUtil.postJson(url + createPayapply, headNamePairs, param, socketTimeout);
            interfaceLogUtil.setCallPartySuccessLog(interfaceLog, strReturn);

            if (!StringUtils.isEmpty(strReturn)) {
                RestfulResponse<String> shipTaskVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<String>>() {
                });
                if (shipTaskVO == null) {
                    interfaceLogUtil.setErrorLog(interfaceLog, "没有数据");
                    throw new BaseException("同步失败");
                } else if (!Objects.deepEquals(shipTaskVO.getCode(), 0)) {
                    interfaceLogUtil.setErrorLog(interfaceLog, shipTaskVO.getMessage());
                    throw new BaseException("油卡支付创建车队支付申请异常：" + shipTaskVO.getMessage());
                }
                interfaceLogUtil.setSuccessLog(interfaceLog);
                stringRestfulResponse = shipTaskVO;
            }

            interfaceLogUtil.saveInterfaceLog(interfaceLog);
            return stringRestfulResponse;
        } catch (BaseException e) {
            interfaceLogUtil.saveInterfaceLog(interfaceLog);
            throw e;
        } catch (Exception e) {
            interfaceLogUtil.saveInterfaceLog(interfaceLog);
            throw new BaseException("油卡支付创建车队支付申请异常");
        }
    }

    /**
     * 根据applyNO获取对应油卡支付信息
     *
     * @param applyNO
     * @return
     */
    public RestfulResponse<FcPayApplyReturnDTO> getPayApplyAudit(String applyNO) {
        RestfulResponse<FcPayApplyReturnDTO> stringRestfulResponse = new RestfulResponse<>();
        if (!StringUtils.isEmpty(applyNO)) {
            String token = this.getToken();
            InterfaceLog interfaceLog = new InterfaceLog();
            try {
                List<NameValuePair> headNamePairs = Lists.newArrayList();
                headNamePairs.add(new BasicNameValuePair("Authorization", "Bearer " + token));
                // 发送请求
                interfaceLogUtil.setCallerPartyCommonLog(interfaceLog, applyNO, url + getPayApplyAudit);

                String strReturn = HttpClientUtil.get(url + getPayApplyAudit + applyNO, headNamePairs, new ArrayList<>(), socketTimeout);
                interfaceLogUtil.setCallPartySuccessLog(interfaceLog, strReturn);

                if (!StringUtils.isEmpty(strReturn)) {
                    RestfulResponse<FcPayApplyReturnDTO> shipTaskVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<FcPayApplyReturnDTO>>() {
                    });
                    if (shipTaskVO == null) {
                        interfaceLogUtil.setErrorLog(interfaceLog, "没有数据");
                        throw new BaseException("同步失败");
                    } else if (!Objects.deepEquals(shipTaskVO.getCode(), 0)) {
                        interfaceLogUtil.setErrorLog(interfaceLog, shipTaskVO.getMessage());
                        throw new BaseException("查询支付申请单号审核状态：" + shipTaskVO.getMessage());
                    }
                    interfaceLogUtil.setSuccessLog(interfaceLog);
                    stringRestfulResponse = shipTaskVO;
                }

                interfaceLogUtil.saveInterfaceLog(interfaceLog);
                return stringRestfulResponse;
            } catch (BaseException e) {
                interfaceLogUtil.saveInterfaceLog(interfaceLog);
                throw e;
            } catch (Exception e) {
                interfaceLogUtil.saveInterfaceLog(interfaceLog);
                throw new BaseException("油卡支付创建车队支付申请异常");
            }
        }
        return stringRestfulResponse;
    }
}
